import 'dart:async';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:common_utils/common_utils.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/verification_vo.dart';

class UpdatePayPassowrdPageController extends GetxController {

  final CommonPageController commonPageController = Get.find();
  
  /// 密码
  var password = ''.obs;
  /// 校验密码
  var checkPassword = true.obs;
  /// 确认密码
  var confirmPassword = ''.obs;
  /// 校验确认密码
  var checkConfirmPassword = true.obs;
  /// 验证码
  var verificationCode = ''.obs;
  /// 校验验证码
  var checkVerificationCode = true.obs;
  /// 剩余秒数
  var duration = 60.obs;
  /// 时间倒计时
  Timer? _timer;
  String verificationKey = '';

  /// 校验修改密码
  checkUpdatePassword() {
    var _regExp=r'^[0-9]{6}$';
    if (!RegExp(_regExp).hasMatch(password.value)) {
      checkPassword.value = false;
      return false;
    }
    checkPassword.value = true;
    return true;
  }

  /// 校验确认密码
  checkConfirmPasswordFun() {
    if (TextUtil.isEmpty(confirmPassword.value) || password.value != confirmPassword.value) {
      checkConfirmPassword.value = false;
      return false;
    }
    checkConfirmPassword.value = true;
    return true;
  }

  /// 校验验证码
  checkVerificationCodeFun() {
    if (TextUtil.isEmpty(verificationCode.value) || verificationCode.value.length < 6) {
      checkVerificationCode.value = false;
      return false;
    }
    checkVerificationCode.value = true;
    return true;
  }

  /// 获取验证码
  getSmsCode() async {
    VerificationVo? res = await HttpUtilService.getVerificationCode(mobile: commonPageController.userData.value.mobile!, type: 'pay_password');
    if (res == null) {
      return;
    }
    EasyLoading.showToast('发送成功');
    verificationKey = res.data!.verificationKey!;
    _timer?.cancel();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      duration.value--;
      print('duration.value: ${duration.value }');
      if (duration.value == 0) {
        _timer?.cancel();
        duration.value = 60;
      }
    });
  }

  /// 修改密码
  editPassword() async {
    if (!checkUpdatePassword()) {
      return;
    }
    if (!checkConfirmPasswordFun()) {
      return;
    }
    if (!checkVerificationCodeFun()) {
      return;
    }
    bool res = await HttpUtilService.updatePayPassword(verificationCode: verificationCode.value, password: password.value, verificationKey: verificationKey);
    if (res) {
      Get.back();
      EasyLoading.showToast('修改成功');
      commonPageController.checkLogin(loading: false);
    }
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

}